package com.yunlinker.baseclass;

import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.UMShareAPI;
import com.yunlinker.auth.WebPermissionManager;
import com.yunlinker.hotupdate.HotUpdateManager;
import com.yunlinker.manager.ActivityResult;

import com.yunlinker.myApp;
import com.yunlinker.util.Constant;
import com.yunlinker.util.DeviceConnFactoryManager;
import com.yunlinker.util.ThreadPool;
import com.yunlinker.util.Utils;
import com.yunlinker.xxc.BluetoothDeviceList;
import com.yunlinker.xxc.JSInspect;
import com.yunlinker.xxc.R;

import woyou.aidlservice.jiuiv5.IWoyouService;

import static android.hardware.usb.UsbManager.ACTION_USB_DEVICE_ATTACHED;
import static android.hardware.usb.UsbManager.ACTION_USB_DEVICE_DETACHED;
import static com.yunlinker.config.WebConfig.AssestRoot;
import static com.yunlinker.util.Constant.ACTION_USB_PERMISSION;
import static com.yunlinker.util.Constant.CONN_STATE_DISCONN;
import static com.yunlinker.util.Constant.MESSAGE_UPDATE_PARAMETER;
import static com.yunlinker.util.DeviceConnFactoryManager.ACTION_QUERY_PRINTER_STATE;
import static com.yunlinker.util.DeviceConnFactoryManager.CONN_STATE_FAILED;


/**
 * Created by lemon on 2017/7/26.
 */

public class BaseActivity extends AppCompatActivity {
    private static final int REQUEST_CODE_SCAN = 0x0000;

    /**
     * 使用打印机指令错误
     */
    private static final int PRINTER_COMMAND_ERROR = 0x008;

    private static final int CONN_PRINTER = 0x12;
    private static final int CONN_MOST_DEVICES = 0x11;
    public static String tempcode;

    public String loadUrl;

    protected BaseWebView mwebView;
    private ImageView splash;

    public BaseWebView getWebView() {
        return mwebView;
    }
    private Handler handler;
    public LinearLayout rootlay;
    private ThreadPool threadPool;
    private BluetoothAdapter mBluetoothAdapter;
    private Context thisCon=null;
    public static Handler handlerprint;
    private int id = 0;
    Context mContext;

    public IWoyouService woyouService;

    public myApp baseApp;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
                WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
        //FullScreen.fullScreen(this);
        rootlay = new LinearLayout(this);
        setContentView(rootlay);
        addWebView();
        baseApp = (myApp)getApplication();

        try {
            thisCon=this.getApplicationContext();
            EnableBluetooth();
            handlerprint = new Handler(){
                @Override
                public void handleMessage(Message msg) {
                    // TODO Auto-generated method stub
                    super.handleMessage(msg);
//                    if (msg.what==1) {
//                        Toast.makeText(thisCon, "succeed", Toast.LENGTH_SHORT).show();
//                        dialog.cancel();
//                    }else {
//                        Toast.makeText(thisCon, "failure",Toast.LENGTH_SHORT).show();
//                        dialog.cancel();
//                    }
                    switch (msg.what){
                        case CONN_STATE_DISCONN:
                            if (DeviceConnFactoryManager.getDeviceConnFactoryManagers()[inp.id] != null||!DeviceConnFactoryManager.getDeviceConnFactoryManagers()[inp.id].getConnState()) {
                                DeviceConnFactoryManager.getDeviceConnFactoryManagers()[inp.id].closePort(inp.id);
                                Utils.toast(BaseActivity.this,getString(R.string.str_disconnect_success));
                            }
                            break;
                        case MESSAGE_UPDATE_PARAMETER:
                            String strIp = msg.getData().getString("Ip");
                            String strPort = msg.getData().getString("Port");
                            //初始化端口信息
                            new DeviceConnFactoryManager.Build()
                                    //设置端口连接方式
                                    .setConnMethod(DeviceConnFactoryManager.CONN_METHOD.WIFI)
                                    //设置端口IP地址
                                    .setIp(strIp)
                                    //设置端口ID（主要用于连接多设备）
                                    .setId(id)
                                    //设置连接的热点端口号
                                    .setPort(Integer.parseInt(strPort))
                                    .build();
                            threadPool = ThreadPool.getInstantiation();
                            threadPool.addTask(new Runnable() {
                                @Override
                                public void run() {
                                    DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].openPort();
                                }
                            });
                            break;
                        default:
                            new DeviceConnFactoryManager.Build()
                                    //设置端口连接方式
                                    .setConnMethod(DeviceConnFactoryManager.CONN_METHOD.WIFI)
                                    //设置端口IP地址
                                    .setIp("192.168.0.142")
                                    //设置端口ID（主要用于连接多设备）
                                    .setId(id)
                                    //设置连接的热点端口号
                                    .setPort(9100)
                                    .build();
                            threadPool.addTask(new Runnable() {
                                @Override
                                public void run() {
                                    DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].openPort();
                                }
                            });
                            break;
                        case PRINTER_COMMAND_ERROR:
                            Utils.toast(mContext, getString(R.string.str_choice_printer_command));
                            break;
                    }

                }
            };
        } catch (Exception e) {
            e.printStackTrace();
        }


      //  Binding();


    }

        private void Binding(){
        Intent intent=new Intent();
        intent.setPackage("woyou.aidlservice.jiuiv5");
        intent.setAction("woyou.aidlservice.jiuiv5.IWoyouService");
        bindService(intent, connection, Context.BIND_AUTO_CREATE);
    }
    private ServiceConnection connection =   new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            woyouService = IWoyouService.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            woyouService = null;
        }
    };






    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);

        if (mwebView != null)
            mwebView.resumeWeb();

    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(receiver);
    }

    public AlertDialog dialog;

    @Override
    protected void onPause() {
        super.onPause();
        if (dialog != null) dialog.dismiss();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mwebView != null) {
            mwebView.destroy();
        }
        MobclickAgent.onPause(this);

//        DeviceConnFactoryManager.closeAllPort();
//        if (threadPool != null) {
//            threadPool.stopThreadPool();
//        }

    }

    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_FIRST_USER) {
            switch (requestCode) {
                /*蓝牙连接*/
                case Constant.BLUETOOTH_REQUEST_CODE: {
                    try {
                        closeport();
                        /*获取蓝牙mac地址*/
                        String macAddress = data.getStringExtra(BluetoothDeviceList.EXTRA_DEVICE_ADDRESS);
                        //初始化话DeviceConnFactoryManager
                        new DeviceConnFactoryManager.Build()
                                .setId(inp.id)
                                //设置连接方式
                                .setConnMethod(DeviceConnFactoryManager.CONN_METHOD.BLUETOOTH)
                                //设置连接的蓝牙mac地址
                                .setMacAddress(macAddress)
                                .build();
                        Log.e("111111", "onActivityResult: " + macAddress);
                        //打开端口
                        threadPool = ThreadPool.getInstantiation();
                        threadPool.addTask(new Runnable() {
                            @Override
                            public void run() {
                                DeviceConnFactoryManager.getDeviceConnFactoryManagers()[inp.id].openPort();
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;

                }
                case CONN_MOST_DEVICES:
                    id = data.getIntExtra("id", -1);
                    if (DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id] != null &&
                            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].getConnState()) {
                        Toast.makeText(BaseActivity.this, "连接状态：已连接"+"\n"+ getConnDeviceInfo(), Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(BaseActivity.this, "连接状态：未连接", Toast.LENGTH_SHORT).show();
                    }
                    break;

            }
        } else {
            ActivityResult.getInstance().resultBack(BaseActivity.this, requestCode, resultCode, data);
        }
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {
                String result = data.getStringExtra("codedContent");
                mwebView.setInsCode("scanf", tempcode);
                mwebView.setValue("scanf", result);
            }
        }
    }


    /**
     * 重新连接回收上次连接的对象，避免内存泄漏
     */
    private void closeport() {
        if (DeviceConnFactoryManager.getDeviceConnFactoryManagers()[inp.id] != null && DeviceConnFactoryManager.getDeviceConnFactoryManagers()[inp.id].mPort != null) {
            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[inp.id].new PrinterReader().cancel();
            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[inp.id].mPort.closePort();
            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[inp.id].mPort = null;
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        WebPermissionManager.getInstance(BaseActivity.this).authBack(requestCode, permissions, grantResults);
    }

    @Override
    public void onBackPressed() {
        mwebView.setValue("0", "back");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Boolean backV = true;
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                onBackPressed();
                break;
            case KeyEvent.KEYCODE_MENU:
                break;
            default:
                backV = super.onKeyDown(keyCode, event);
                break;
        }
        return backV;
    }

    //添加webview
    private JSInspect inp = null;

    //获取inspect对象
    public JSInspect jsInp() {
        return inp;
    }

    //添加视图
    protected void addWebView() {

        mwebView = new BaseWebView(this);
        LinearLayout.LayoutParams webLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        mwebView.setLayoutParams(webLayoutParams);
        rootlay.addView(mwebView);

        mwebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);

        mwebView.setHorizontalScrollBarEnabled(false);//水平不显示
        mwebView.setVerticalScrollBarEnabled(false); //垂直不显示
        inp = new JSInspect(mwebView, BaseActivity.this);
        mwebView.addJavascriptInterface(inp, "WeiLai");
        mwebView.setWebViewClient(new BaseClient(mwebView, BaseActivity.this));

        mwebView.setWebContentsDebuggingEnabled(true);

        WebSettings setting = mwebView.getSettings();
        setting.setJavaScriptEnabled(true);//支持js
        setting.setDefaultTextEncodingName("utf-8");
        setting.setDomStorageEnabled(true);
        setting.setAllowFileAccess(true);
        setting.setAllowContentAccess(true);
        setting.setAllowFileAccessFromFileURLs(true);
        setting.setCacheMode(WebSettings.LOAD_DEFAULT);


        loadUrl = getIntent().getStringExtra("sendUrl");
        if (!TextUtils.isEmpty(loadUrl)) {
            if (!loadUrl.startsWith("http") || !loadUrl.startsWith("file"))
                loadUrl = AssestRoot + loadUrl;
            mwebView.loadUrl(loadUrl);
        } else {
            HotUpdateManager.getInstance().checkUpdate(new HotUpdateManager.Listener() {
                @Override
                public void onUpdate(String indexUrl) {
                    //首页
                    mwebView.loadUrl(indexUrl);
                }
            });
        }

        setKeyBoard();
    }

    private int screenHeight = 0;

    private void setKeyBoard() {
        //---------------安卓键盘处理-----------------
        mwebView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                mwebView.getWindowVisibleDisplayFrame(r);
                final int visibleHeight = r.height();
                if (screenHeight == 0) {
                    screenHeight = visibleHeight;
                } else {
                    if (visibleHeight > 100 && screenHeight != visibleHeight) {
                        //有可能为打开键盘
                        mwebView.post(new Runnable() {
                            @Override
                            public void run() {
                                float ratio = (screenHeight - visibleHeight) / (float) screenHeight;
                                mwebView.loadUrl("javascript:window.keyBoardEvent&&keyBoardEvent(1," + ratio + ");");
                            }
                        });
                    } else {
                        //有可能为关闭键盘
                        mwebView.post(new Runnable() {
                            @Override
                            public void run() {
                                mwebView.loadUrl("javascript:window.keyBoardEvent&&keyBoardEvent(0);");
                            }
                        });
                    }
                }
            }
        });
    }


    @Override
    protected void onStart() {
        super.onStart();
        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        filter.addAction(ACTION_USB_DEVICE_DETACHED);
        filter.addAction(ACTION_QUERY_PRINTER_STATE);
        filter.addAction(DeviceConnFactoryManager.ACTION_CONN_STATE);
        filter.addAction(ACTION_USB_DEVICE_ATTACHED);
        registerReceiver(receiver, filter);
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case ACTION_USB_DEVICE_DETACHED:
                    handler.obtainMessage(CONN_STATE_DISCONN).sendToTarget();
                    break;
                case DeviceConnFactoryManager.ACTION_CONN_STATE:
                    int state = intent.getIntExtra(DeviceConnFactoryManager.STATE, -1);
                    int deviceId = intent.getIntExtra(DeviceConnFactoryManager.DEVICE_ID, -1);
                    switch (state) {
                        case DeviceConnFactoryManager.CONN_STATE_DISCONNECT:
                            if (inp.id == deviceId) {
                                Utils.toast(BaseActivity.this, "连接状态：未连接");
                            }
                            break;
                        case DeviceConnFactoryManager.CONN_STATE_CONNECTING:
                            Utils.toast(BaseActivity.this, "连接状态：连接中");
                            break;
                        case DeviceConnFactoryManager.CONN_STATE_CONNECTED:
                            Utils.toast(BaseActivity.this, "连接状态：已连接" + "\n" + getConnDeviceInfo());
                            break;
                        case CONN_STATE_FAILED:
                            Utils.toast(BaseActivity.this, getString(R.string.str_conn_fail));
                            break;
                        default:
                            break;
                    }
                    break;
            }
        }
    };



    private String getConnDeviceInfo() {
        String str = "";
        DeviceConnFactoryManager deviceConnFactoryManager = DeviceConnFactoryManager.getDeviceConnFactoryManagers()[inp.id];
        if (deviceConnFactoryManager != null
                && deviceConnFactoryManager.getConnState()) {
            if ("USB".equals(deviceConnFactoryManager.getConnMethod().toString())) {
                str += "USB\n";
                str += "USB Name: " + deviceConnFactoryManager.usbDevice().getDeviceName();
            } else if ("WIFI".equals(deviceConnFactoryManager.getConnMethod().toString())) {
                str += "WIFI\n";
                str += "IP: " + deviceConnFactoryManager.getIp() + "\t";
                str += "Port: " + deviceConnFactoryManager.getPort();
            } else if ("BLUETOOTH".equals(deviceConnFactoryManager.getConnMethod().toString())) {
                str += "BLUETOOTH\n";
                str += "MacAddress: " + deviceConnFactoryManager.getMacAddress();
            } else if ("SERIAL_PORT".equals(deviceConnFactoryManager.getConnMethod().toString())) {
                str += "SERIAL_PORT\n";
                str += "Path: " + deviceConnFactoryManager.getSerialPortPath() + "\t";
                str += "Baudrate: " + deviceConnFactoryManager.getBaudrate();
            }
        }
        return str;
    }


    private boolean EnableBluetooth() {
        boolean bRet = false;
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(mBluetoothAdapter != null) {
            if(mBluetoothAdapter.isEnabled())
                return true;
            mBluetoothAdapter.enable();
            try
            {
                Thread.sleep(500);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            if(!mBluetoothAdapter.isEnabled()){
                bRet = true;
                Log.d("PRTLIB", "BTO_EnableBluetooth --> Open OK");
            }
        } else {
            Log.d("HPRTSDKSample", (new StringBuilder("Activity_Main --> EnableBluetooth ").append("Bluetooth Adapter is null.")).toString());
        }
        return bRet;
    }

}

